<?php
// 登录安全模块：防止暴力破解
function checkLoginAttempts($username) {
    $lockFile = 'login_locks.json';
    $locks = file_exists($lockFile) ? json_decode(file_get_contents($lockFile), true) : [];
    
    if (isset($locks[$username])) {
        // 添加尝试次数的判断条件
        if ($locks[$username]['attempts'] >= 5) {
            // 检查是否仍在锁定期内（30分钟）
            if (time() - $locks[$username]['timestamp'] < 1800) {
                $remaining = ceil((1800 - (time() - $locks[$username]['timestamp'])) / 60);
                return "账号已被锁定，请{$remaining}分钟后再试";
            } else {
                // 锁定过期，移除记录
                unset($locks[$username]);
                file_put_contents($lockFile, json_encode($locks));
            }
        }
    }
    return null;
}

function recordFailedAttempt($username) {
    $lockFile = 'login_locks.json';
    $locks = file_exists($lockFile) ? json_decode(file_get_contents($lockFile), true) : [];
    
    // 初始化计数器
    if (!isset($locks[$username])) {
        $locks[$username] = [
            'attempts' => 0,
            'timestamp' => time()
        ];
    }
    
    // 增加尝试次数
    $locks[$username]['attempts']++;
    $locks[$username]['timestamp'] = time();
    
    // 超过5次则锁定
    if ($locks[$username]['attempts'] >= 5) {
        $locks[$username]['timestamp'] = time();
    }
    
    file_put_contents($lockFile, json_encode($locks));
}
?>